package com.kehutong.wwin.service.service;

import com.kehutong.common.entity.Root;
import com.kehutong.common.enums.CropPattern;
import com.kehutong.common.util.CorpUtils;
import com.kehutong.wwin.service.entity.Corp;
import org.coraframework.authz.Subject;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.connection.ThreadLocalCache;
import org.coraframework.util.IDGenerate;
import org.coraframework.util.Objects;

import com.kehutong.common.util.Token;
import com.kehutong.wwin.service.entity.EmployeeMap;
import com.kehutong.wwin.service.util.WwInHttpClient;

import java.util.Arrays;

@WebService("/wwin/event/change_contact")
public class ToKhtEmployeeService {

	static final Logger logger = LoggerFactory.getLogger(ToKhtEmployeeService.class);

	@Inject
	private JdbcSession jdbcSession;
	@Inject
	private WwInHttpClient httpClient;
	@Inject
	private ToKhtDepartmentService khtDepartmentService;

	@ReqMapping("/create_user")
	public Object create(Token token, JSONObject wwJson) throws Exception {
		String cropId=wwJson.getString("ToUserName");
		Corp crop = Pool.get(Corp.class, cropId);
		ThreadLocalCache.current().setCorpId(crop.getKhtid());
		EmployeeMap employee = createEmployee(wwJson);
		if(CorpUtils.getCropPattern(crop.getKhtid())== CropPattern.INNER){
			JSONObject rs = httpClient.postKht("/basic/employee/service/save", cropId, http-> {
				JSONObject toKhtJson = employee.toKhtJson();
				http.setBody(toKhtJson.toJSONString());
			});

			int result = rs.getIntValue("code");
			if (result != 200) {
				return Result.error(result, rs.getString("message"));
			}
		}
		jdbcSession.insert(employee);
		return Result.success(employee);
	}


	@ReqMapping("/update_user")
	public Object update(Token token, JSONObject wwJson) throws Exception {
		String cropId=wwJson.getString("ToUserName");
		Corp crop = Pool.get(Corp.class, cropId);
		ThreadLocalCache.current().setCorpId(crop.getKhtid());
		EmployeeMap employee = getUpdateEmployee(wwJson);
		if(CorpUtils.getCropPattern(crop.getKhtid())== CropPattern.INNER){
			JSONObject rs = httpClient.postKht("/basic/employee/service/update", cropId, http-> {
				JSONObject toKhtJson = employee.toKhtJson();
				http.setBody(toKhtJson.toJSONString());
			});

			int result = rs.getIntValue("code");
			if (result != 200) {
				return Result.error(result, rs.getString("message"));
			}
		}
		return Result.success();
	}

	@ReqMapping("/delete_user")
	public Object delete(Token token, JSONObject wwJson) throws Exception {
		String cropId=wwJson.getString("ToUserName");
		Corp crop = Pool.get(Corp.class, cropId);
		ThreadLocalCache.current().setCorpId(crop.getKhtid());
		EmployeeMap employee = getEmployeeByWwId(wwJson.getString("UserID"));
		if(CorpUtils.getCropPattern(crop.getKhtid())== CropPattern.INNER){
			JSONObject rs = httpClient.postKht("/basic/employee/service/update", cropId, http-> {
				http.addParam("id", employee.getKhtid());
			});

			int result = rs.getIntValue("code");
			if (result != 200) {
				return Result.error(result, rs.getString("message"));
			}
		}
		jdbcSession.deleteById(employee);
		return Result.success();
	}
	
	public void save(EmployeeMap save) {
		jdbcSession.insert(save);
	}

	public EmployeeMap getEmployeeByWwId(String userid) {
		return Pool.get(EmployeeMap.class, userid);
	}
	
	private EmployeeMap getUpdateEmployee(JSONObject wwJson) {
		String userId = wwJson.getString("UserID");
		String newuserId = wwJson.getString("NewUserID");
		
		final EmployeeMap employee = getEmployee(wwJson);
		if (Objects.isEmpty(newuserId) || !newuserId.equals(userId)) {
			return employee;
		}
		
		wwJson.put("UserID", newuserId);
		final EmployeeMap newEmployee = createEmployee(wwJson);
		newEmployee.setKhtid(employee.getKhtid());
		jdbcSession.insert(newEmployee);
		jdbcSession.deleteById(employee);
		
		return newEmployee;
	}

	private EmployeeMap createEmployee(JSONObject wwJson) {
		JSONArray wwJsonArray = getDepartment(wwJson);
		//授权微信企业的CorpID
		String cropId=wwJson.getString("ToUserName");
		Corp crop = Pool.get(Corp.class, cropId);
		EmployeeMap item = Pool.newInstance(EmployeeMap.class, wwJson.getString("UserID"));

		item.setUserId(wwJson.getString("UserID"));
		item.setName(wwJson.getString("Name"));

		item.setDepartments(khtDepartmentService.getKhtIdByWwinId(wwJsonArray));
		String mainDepartment=khtDepartmentService.getKhtIdByWwinId(wwJson.getString("MainDepartment"));
		item.setMainDepartment(Objects.isEmpty(mainDepartment)? Integer.parseInt(Root.ROOT_ID):Integer.parseInt(mainDepartment));
		item.setMobile(wwJson.getString("Mobile"));
		item.setGender(wwJson.getString("Gender"));
		item.setEmail(wwJson.getString("Email"));
		item.setAvatar(wwJson.getString("Avatar"));
		item.setTelephone(wwJson.getString("Telephone"));
		item.setAddress(wwJson.getString("Address"));
		item.setKhtid(toKhtId(crop.getKhtid(),item.getUserId()));

		return item;
	}

	private JSONArray getDepartment(JSONObject wwJson) {
		JSONArray result = null;
		try {
			result = wwJson.getJSONArray("Department");
		} catch (Exception e) {
			logger.info("部门数据有误");
			String department = wwJson.getString("Department");
			if (department != null) {
				result = new JSONArray();
				String[] departments = department.split(",");
				result.addAll(Arrays.asList(departments));
			}
		}
		return result;
	}
	private EmployeeMap getEmployee(JSONObject wwJson) {
		logger.info("员工信息wwJson=" + wwJson.toJSONString());
		EmployeeMap item = getEmployeeByWwId(wwJson.getString("UserID"));
		if (item == null) {
			return null;
		}
		String newUserID = wwJson.getString("NewUserID");
		if (Objects.nonEmpty(newUserID)) {
			item.setUserId(newUserID);
		} else {
			item.setUserId(wwJson.getString("UserID"));
		}
		JSONArray wwJsonArray = getDepartment(wwJson);
		item.setName(wwJson.getString("Name"));
		item.setDepartments(khtDepartmentService.getKhtIdByWwinId(wwJsonArray));
		String mainDepartment=khtDepartmentService.getKhtIdByWwinId(wwJson.getString("MainDepartment"));
		item.setMainDepartment(Objects.isEmpty(mainDepartment)?Integer.parseInt(Root.ROOT_ID):Integer.parseInt(mainDepartment));
		item.setMobile(wwJson.getString("Mobile"));
		item.setGender(wwJson.getString("Gender"));
		item.setEmail(wwJson.getString("Email"));
		item.setAvatar(wwJson.getString("Avatar"));
		item.setTelephone(wwJson.getString("Telephone"));
		item.setAddress(wwJson.getString("Address"));

		return item;
	}

	public static String toKhtId(String corpNo, String userId) {
		StringBuilder buf = new StringBuilder(corpNo).append("_").append(userId.toUpperCase());
		return Subject.encrypt(buf.toString());
	}

	@ReqMapping("/getEmployeeByKhtIds")
	public Object getEmployeeByKhtIds(JSONObject jsonObject) {
		return jdbcSession.findArray(EmployeeMap.class)
				.in("khtid", jsonObject.getJSONArray("khtIds"))
				.exe();
	}

}
